<template>
  <div class="preview-page">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="back-btn" @click="goBack">
        <svg
          width="24"
          height="24"
          viewBox="0 0 24 24"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path
            d="M15 18L9 12L15 6"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
          />
        </svg>
      </div>
      <div class="title">图片预览</div>
      <div class="placeholder"></div>
    </div>

    <!-- 图片预览区域 -->
    <div
      class="image-container"
      ref="imageContainer"
      @wheel="onWheel"
      @touchstart="onTouchStart"
      @touchmove="onTouchMove"
      @touchend="onTouchEnd"
    >
      <div
        class="image-wrapper"
        :style="{
          transform: `translateY(${translateY}px) scale(${scale})`,
          transition: isAnimating ? 'transform 0.2s ease-out' : 'none',
        }"
        @dblclick="toggleZoom"
      >
        <img
          :src="imgurl"
          alt="预览图片"
          class="preview-image"
          @load="onImageLoad"
          @error="onImageError"
          v-show="!isLoading && !hasError"
        />
      </div>

      <!-- 加载状态 -->
      <div class="loading" v-show="isLoading">
        <div class="spinner"></div>
        <p>图片加载中...</p>
      </div>

      <!-- 错误状态 -->
      <div class="error" v-show="hasError">
        <div class="error-icon">!</div>
        <p>图片加载失败</p>
        <button class="retry-btn" @click="retryLoad">重新加载</button>
      </div>
    </div>

    <!-- 返回首页按钮 -->
    <div class="home-btn-container">
      <button class="home-btn" @click="goHome">返回首页</button>
    </div>

    <!-- 操作提示 -->
    <!-- <div class="hint" v-show="!isLoading && !hasError">
      双击放大/缩小 • 滚轮/滑动查看长图
    </div> -->
  </div>
</template>

<script>
export default {
  name: "ImagePreview",
  data() {
    return {
      imgurl: "",
      isLoading: true,
      hasError: false,
      translateY: 0,
      scale: 1,
      startY: 0,
      isDragging: false,
      maxTranslate: 0,
      minTranslate: 0,
      originalBodyOverflow: "",
      isAnimating: false,
      velocity: 0,
      lastY: 0,
      lastTime: 0,
      inertiaTimer: null,
    };
  },
  created() {
    this.imgurl = this.$route.query.imgurl;
  },
  mounted() {
    this.initTouchEvents();
    window.addEventListener("resize", this.calculateScrollRange);
  },
  methods: {
    goBack() {
      this.$router.go(-1);
    },

    goHome() {
      this.$router.push("/managerHome");
    },

    onImageLoad() {
      this.isLoading = false;
      this.hasError = false;
      this.$nextTick(() => {
        this.calculateScrollRange();
      });
    },

    onImageError() {
      this.isLoading = false;
      this.hasError = true;
    },

    retryLoad() {
      this.isLoading = true;
      this.hasError = false;
      const img = new Image();
      img.onload = () => {
        this.onImageLoad();
      };
      img.onerror = () => {
        this.onImageError();
      };
      img.src = this.imgurl;
    },

    initTouchEvents() {
      this.originalBodyOverflow = document.body.style.overflow;
      document.body.style.overflow = "hidden";
    },

    onWheel(e) {
      e.preventDefault();

      if (this.scale === 1) {
        // 在正常缩放模式下，使用滚轮滚动
        const delta = e.deltaY;
        const step = 40; // 滚轮步长

        let newTranslateY = this.translateY + delta;

        // 应用缓动效果
        this.isAnimating = true;
        newTranslateY = Math.max(
          this.minTranslate,
          Math.min(this.maxTranslate, newTranslateY)
        );

        this.translateY = newTranslateY;

        // 清除之前的定时器
        if (this.inertiaTimer) {
          clearTimeout(this.inertiaTimer);
        }

        // 设置动画结束
        this.inertiaTimer = setTimeout(() => {
          this.isAnimating = false;
        }, 200);
      }
    },

    onTouchStart(e) {
      this.isDragging = true;
      this.isAnimating = false;
      this.startY = e.touches[0].clientY;
      this.lastY = this.startY;
      this.lastTime = Date.now();
      this.velocity = 0;

      // 清除惯性定时器
      if (this.inertiaTimer) {
        clearTimeout(this.inertiaTimer);
      }
    },

    onTouchMove(e) {
      if (!this.isDragging) return;

      const currentY = e.touches[0].clientY;
      const currentTime = Date.now();
      const deltaTime = currentTime - this.lastTime;

      if (deltaTime > 0) {
        const deltaY = currentY - this.lastY;
        this.velocity = deltaY / deltaTime;
        this.lastY = currentY;
        this.lastTime = currentTime;
      }

      const deltaY = currentY - this.startY;

      // 检查是否需要阻止默认行为（防止页面滚动）
      const container = this.$refs.imageContainer;
      const img = container.querySelector(".preview-image");

      if (img) {
        const imgHeight = img.clientHeight * this.scale;
        const containerHeight = container.clientHeight;

        if (imgHeight > containerHeight || this.scale > 1) {
          e.preventDefault();
        }
      }

      let newTranslateY = this.translateY + deltaY;

      // 边界检查，添加弹性效果
      if (newTranslateY > this.maxTranslate + 50) {
        newTranslateY =
          this.maxTranslate +
          50 -
          (newTranslateY - (this.maxTranslate + 50)) * 0.3;
      } else if (newTranslateY < this.minTranslate - 50) {
        newTranslateY =
          this.minTranslate -
          50 +
          (this.minTranslate - 50 - newTranslateY) * 0.3;
      } else {
        newTranslateY = Math.max(
          this.minTranslate,
          Math.min(this.maxTranslate, newTranslateY)
        );
      }

      this.translateY = newTranslateY;
      this.startY = currentY;
    },

    onTouchEnd() {
      if (!this.isDragging) return;

      this.isDragging = false;

      // 惯性滑动效果
      if (Math.abs(this.velocity) > 0.1) {
        this.applyInertia();
      } else {
        this.snapToBounds();
      }
    },

    applyInertia() {
      const friction = 0.95;
      const minVelocity = 0.1;

      const applyInertiaFrame = () => {
        if (Math.abs(this.velocity) < minVelocity) {
          this.snapToBounds();
          return;
        }

        this.velocity *= friction;

        let newTranslateY = this.translateY + this.velocity * 16;

        // 边界检查
        if (newTranslateY > this.maxTranslate) {
          newTranslateY = this.maxTranslate;
          this.velocity = 0;
        } else if (newTranslateY < this.minTranslate) {
          newTranslateY = this.minTranslate;
          this.velocity = 0;
        }

        this.translateY = newTranslateY;

        if (Math.abs(this.velocity) >= minVelocity) {
          requestAnimationFrame(applyInertiaFrame);
        } else {
          this.snapToBounds();
        }
      };

      requestAnimationFrame(applyInertiaFrame);
    },

    snapToBounds() {
      this.isAnimating = true;

      let newTranslateY = Math.max(
        this.minTranslate,
        Math.min(this.maxTranslate, this.translateY)
      );

      this.translateY = newTranslateY;

      setTimeout(() => {
        this.isAnimating = false;
      }, 300);
    },

    toggleZoom() {
      this.isAnimating = true;

      if (this.scale === 1) {
        this.scale = 2;
        this.translateY = 0;
      } else {
        this.scale = 1;
      }

      this.$nextTick(() => {
        this.calculateScrollRange();
        setTimeout(() => {
          this.isAnimating = false;
        }, 300);
      });
    },

    calculateScrollRange() {
      if (!this.$refs.imageContainer) return;

      const container = this.$refs.imageContainer;
      const img = container.querySelector(".preview-image");

      if (!img) return;

      const containerHeight = container.clientHeight;
      const imgHeight = img.clientHeight * this.scale;

      if (imgHeight > containerHeight) {
        // 图片高度大于容器高度，可以上下滚动
        this.maxTranslate = 0;
        this.minTranslate = containerHeight - imgHeight;
      } else {
        // 图片高度小于容器高度，居中显示
        this.maxTranslate = 0;
        this.minTranslate = 0;
        this.translateY = (containerHeight - imgHeight) / 2;
      }

      // 确保当前位置在有效范围内
      this.translateY = Math.max(
        this.minTranslate,
        Math.min(this.maxTranslate, this.translateY)
      );
    },

    cleanup() {
      document.body.style.overflow = this.originalBodyOverflow || "";
      window.removeEventListener("resize", this.calculateScrollRange);

      if (this.inertiaTimer) {
        clearTimeout(this.inertiaTimer);
      }
    },
  },
  beforeDestroy() {
    this.cleanup();
  },

  beforeRouteLeave(to, from, next) {
    this.cleanup();
    next();
  },
};
</script>

<style scoped>
.preview-page {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  touch-action: none;
}

/* 顶部导航栏 */
.header {
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  z-index: 10;
}

.back-btn {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  cursor: pointer;
  -webkit-tap-highlight-color: transparent;
}

.title {
  font-size: 18px;
  font-weight: 500;
}

.placeholder {
  width: 40px;
  height: 40px;
}

/* 图片容器 */
.image-container {
  flex: 1;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  cursor: grab;
  user-select: none;
  -webkit-user-select: none;
}

.image-container:active {
  cursor: grabbing;
}

.image-wrapper {
  will-change: transform;
  transform-origin: center center;
}

.preview-image {
  max-width: 100%;
  display: block;
  transition: opacity 0.3s;
  pointer-events: none;
}

/* 返回首页按钮 */
.home-btn-container {
  position: absolute;
  bottom: 40px;
  left: 0;
  width: 100%;
  display: flex;
  justify-content: center;
  z-index: 5;
}

.home-btn {
  background: #40a2f4;
  color: white;
  border: none;
  padding: 12px 30px;
  border-radius: 25px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.home-btn:active {
  background-color: rgba(255, 255, 255, 0.7);
  transform: scale(0.95);
}

/* 加载状态 */
.loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #fff;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-top: 4px solid #fff;
  border-radius: 50%;
  margin: 0 auto 16px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.loading p {
  margin: 0;
  font-size: 16px;
}

/* 错误状态 */
.error {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #fff;
}

.error-icon {
  width: 60px;
  height: 60px;
  border: 2px solid #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 16px;
  font-size: 28px;
  font-weight: bold;
}

.error p {
  margin: 0 0 20px;
  font-size: 16px;
}

.retry-btn {
  background-color: rgba(255, 255, 255, 0.2);
  border: none;
  border-radius: 20px;
  color: #fff;
  padding: 10px 20px;
  font-size: 14px;
  cursor: pointer;
}

/* 操作提示 */
.hint {
  position: absolute;
  bottom: 20px;
  left: 0;
  width: 100%;
  text-align: center;
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  padding: 0 16px;
  z-index: 5;
}

/* 移动端优化 */
@media (max-width: 768px) {
  .home-btn {
    padding: 14px 28px;
    font-size: 16px;
  }

  .hint {
    bottom: 90px;
  }
}
</style>
